import { onMessage } from 'webext-bridge/background'
import type { Runtime, Tabs } from 'webextension-polyfill'
import { backgroundAuthHandler } from './auth-handler'

// 使用全局认证处理器实例
try {
  backgroundAuthHandler.isAuthenticated()
}
catch (error) {
  console.error('❌ Main.ts: 检查认证状态时出错:', error)
}

// only on dev mode
if (import.meta.hot) {
  // @ts-expect-error for background HMR
  import('/@vite/client')
  // load latest content script
  import('./contentScriptHMR')
}

// remove or turn this off if you don't use side panel
const USE_SIDE_PANEL = true

// to toggle the sidepanel with the action button in chromium:
if (USE_SIDE_PANEL) {
  // @ts-expect-error missing types
  browser.sidePanel
    .setPanelBehavior({ openPanelOnActionClick: true })
    .catch((error: unknown) => console.error(error))
}

browser.runtime.onInstalled.addListener((): void => {

  // console.log('Extension installed')
})

let previousTabId = 0

// communication example: send previous tab title from background page
// see shim.d.ts for type declaration
browser.tabs.onActivated.addListener(async ({ tabId }) => {
  if (!previousTabId) {
    previousTabId = tabId
    return
  }

  let _tab: Tabs.Tab

  try {
    _tab = await browser.tabs.get(previousTabId)
    previousTabId = tabId
  }
  catch {

  }

  // console.log('previous tab', _tab)
  // sendMessage('tab-prev', { title: _tab.title }, { context: 'content-script', tabId })
})

onMessage('get-current-tab', async () => {
  try {
    const tab = await browser.tabs.get(previousTabId)
    return {
      title: tab?.title,
    }
  }
  catch {
    return {
      title: undefined,
    }
  }
})

// 监听打开侧边栏
browser.runtime.onMessage.addListener((message: any, sender: Runtime.MessageSender) => {
  if (message.action === 'openSidebar') {
    try {
      // 存储channelId
      browser.storage.local.set({ currentChannelId: message.channelId })
      // @ts-expect-error Chrome API
      return browser.sidePanel.open({ windowId: sender.tab?.windowId })
    }
    catch (error: any) {
      console.error('Failed to open sidebar:', error)
      return Promise.resolve({ success: false, error: error.message })
    }
  }
  if (message.action === 'get-channel-id') {
    return browser.storage.local.get('currentChannelId')
  }
  return true
})
